package javabase.schoolwork.day6_11;

/**
 * @author fance
 * @date 2018/6/12 8:50
 */
public class ATM {
    private Bank bank;
    private String currentUser;
    private boolean loginStatus;

    public ATM(String bankName) {
        bank = Bank.getBank();
        bank.setName(bankName);
    }

    public void menu() {
        System.out.println("欢迎使用" + bank.getName() + "ATM系统");
        System.out.println("---------------------------------");
        System.out.println("1:用户登录");
        System.out.println("2:查询余额");
        System.out.println("3:存钱");
        System.out.println("4:取钱");
        System.out.println("5:退出");
        System.out.println("---------------------------------");
    }

    public boolean login(String username, String password) {
        Account account = bank.queryAccount(username);
        if (account == null) {
            System.out.println("账户不存在！");
            return false;
        }

        if (!account.getPwd().equals(password)) {
            System.out.println("密码错误！");
            return false;
        }

        currentUser = username;
        loginStatus = true;
        System.out.println("登录成功！");
        return true;
    }

    public boolean queryBalance() {
        if (!loginStatus) {
            System.out.println("未登录。。。");
            return false;
        }

        double balance = bank.queryAccount(currentUser).queryBalance();
        System.out.println("余额：" + balance);
        return true;
    }

    public synchronized boolean withDraw(double amount) {
        if (!loginStatus) {
            System.out.println("非法进入，还未登录！");
            return false;
        }
        Account account = bank.queryAccount(currentUser);
        boolean result = account.withDraw(amount);
        if (!result) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return false;
        }
        notify();
        System.out.println("您取出：" + amount + "  余额：" + account.queryBalance());
        return true;
    }
    public synchronized boolean deposit(double amount) {
        if (!loginStatus) {
            System.out.println("非法进入，还未登录！");
            return false;
        }
        Account account = bank.queryAccount(currentUser);
        boolean result = account.deposit(amount);
        if (!result) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return false;
        }
        notify();
        System.out.println("您存入：" + amount + "  余额：" + account.queryBalance());
        return true;
    }

    public void logout() {
        System.out.println("成功退出系统。。");
        loginStatus = false;
    }
}
